//
// $Id: EngineIO.java 8 2007-04-18 13:47:40Z z_hossain $
//
// xChess is a multiplatform graphical chess user interface
// Copyright (C) 2007  MD. Z. Hossain <z_hossain@users.sf.net>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
// 02110-1301, USA.
//
// For more information visit http://xchess.sourceforge.net
//

package net.sourceforge.xchess;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class EngineIO {
	
	private Process process;
	private BufferedReader reader;
	private PrintWriter writer;
	private String command;
	
	public EngineIO(String command) {
		this.command = command;
		start();
	}
	
	private void start() {
		Runtime runtime = Runtime.getRuntime();
		try {
			process = runtime.exec(command);
			reader = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			writer = new PrintWriter(new OutputStreamWriter(
					process.getOutputStream()), true);
			runtime.addShutdownHook(new Thread() {
				@Override
				public void run() {
					shutdownPerformed();
				}
			});
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	private void shutdownPerformed() {
		if(writer != null) {
			writeLine("quit");
			writer.close();
		}
		process.destroy();
	}
	
	public String readLine() throws IOException {
		String string = reader.readLine();
		if(string != null) System.out.println(string);
		return string;
	}

	public void writeLine(String string) {
		System.out.println(string);
		writer.println(string);
	}
	
	public void restart() {
		process.destroy();
		start();
	}
	
	public void destroy() {
		process.destroy();
	}

	public Process getProcess() {
		return process;
	}

	public String getCommand() {
		return command;
	}
}
